var FM_autocadDatabase_utils = Class.create();
FM_autocadDatabase_utils.prototype = {
    initialize: function () {
    },

    type: 'FM_autocadDatabase_utils',

    getGeoJSONLayerConfiguration: function () {

        var gr = new GlideRecord('x_lsmcb_fm_layer_config');
        gr.addQuery('target_format', 'geojson');
        gr.addQuery('source', 'autocad');
        gr.query();
        if (gr.next()) {
            this.geoJSONLayersConfSysId = gr.getUniqueValue();
            return gr.getValue('file_layers').split(',');
        }
    },

    getSVGLayerConfiguration: function () {

        var gr = new GlideRecord('x_lsmcb_fm_layer_config');
        gr.addQuery('target_format', 'svg');
        gr.addQuery('source', 'autocad');
        gr.query();
        if (gr.next()) {
            this.SVGLayersConfSysId = gr.getUniqueValue();
            return gr.getValue('file_layers').split(',');
        }
    },

    //Saves the svg string to the table
    saveSVG: function (versionSysId, SVG, bgGeoJSON) {

        var content = SVG;
        var contentType = 'image/svg+xml';
        var fileName = 'image';
        var layerSysId = '';

        var gr = new GlideRecord('x_lsmcb_fm_layer');
        gr.addQuery('version', versionSysId);
        gr.addQuery('layer_configuration', this.SVGLayersConfSysId);
        gr.query();
        if (gr.next()) {
            layerSysId = gr.update();
        } else {
            gr = new GlideRecord('x_lsmcb_fm_layer');
            gr.initialize();
            gr.setValue('order', 100);
            gr.setValue('layer_configuration', this.SVGLayersConfSysId);
            gr.setValue('geojson', JSON.stringify(bgGeoJSON));
            gr.setValue('version', versionSysId);
            layerSysId = gr.insert();
        }

        //create the attachment in the sys_attachment table
        var gsaFloorImage = new GlideSysAttachment();
        var attachmentId = gsaFloorImage.write(gr, fileName, contentType, content);
        new FMFloorUtils().setDimentionsFromConverter(layerSysId);

        return attachmentId;
    },

    saveGeoJSON: function (versionSysId, geoJSONList) {

        var gr = new GlideRecord('x_lsmcb_fm_layer');
        gr.addQuery('version', versionSysId);
        gr.addQuery('layer_configuration', this.geoJSONLayersConfSysId);
        gr.query();
        if (gr.next()) {
            gr.setValue('geojson', JSON.stringify(geoJSONList));
            return gr.update();
        }

        gr = new GlideRecord('x_lsmcb_fm_layer');
        gr.initialize();
        gr.setValue('order', 100);
        gr.setValue('layer_configuration', this.geoJSONLayersConfSysId);
        gr.setValue('geojson', JSON.stringify(geoJSONList));
        gr.setValue('version', versionSysId);
        return gr.insert();
    },

    generateFacilities: function (versionSysID, roomList, isNewFloor, building, floor) {

        // Check the Autocad Property 'autocad_autocreate_facilities'
        if (gs.getProperty('x_lsmcb_fm.autocad_autocreate_facilities') == 'false')
            return true;

        if (typeof building != 'undefined' && typeof floor != 'undefined') {

            var floorID = building + '.' + floor;
            var grFloor = new GlideRecord('x_lsmcb_fm_floor');

            var grFloorVersion = new GlideRecord('x_lsmcb_fm_version');
            grFloorVersion.get(versionSysID);

            var buildingSysID = '';
            var floorSysID = '';

            //Create new floor
            if (isNewFloor) {

                //Check if a floor with this ID already exists
                var grFloorCheck = new GlideRecord('x_lsmcb_fm_floor');
                grFloorCheck.addQuery('id', floorID);
                grFloorCheck.query();
                if (grFloorCheck.next())
                    return false;

                var grBuilding = new GlideRecord('x_lsmcb_fm_building');
                grBuilding.addQuery('id', building);
                grBuilding.query();

                if (grBuilding.next()) {
                    buildingSysID = grBuilding.getUniqueValue();

                } else {
                    var grNewBuilding = new GlideRecord('x_lsmcb_fm_building');
                    grNewBuilding.initialize();
                    grNewBuilding.setValue('id', building);
                    grNewBuilding.setValue('name', building);
                    buildingSysID = grNewBuilding.insert();
                }

                grFloor.initialize();
                grFloor.setValue('id', floorID);
				
				// Changed because of kiosk dropdown value fetching 
				// grFloor.setValue('name', floor);
				grFloor.setValue('name', floorID);
				
                grFloor.setValue('building', buildingSysID);
                floorSysID = grFloor.insert();

                //update new values to the version record
                var versionNumber = floorID + ".000";

                grFloorVersion.setValue('record', floorSysID);
                grFloorVersion.setValue('name', floor + " - " + versionNumber);
                grFloorVersion.setValue('version', versionNumber);
                grFloorVersion.update();

                //update the filename to match the floor ID
                var globalAutoCAD_Utils = new global.FM_AutoCAD_Utils();
                globalAutoCAD_Utils.renameAttachments(versionSysID, floorID);

            } else {
                floorSysID = grFloorVersion.getValue('record');
                grFloor.get(floorSysID);
                buildingSysID = grFloor.getValue('building');
            }

            if (roomList.length > 0) {
                var grRoom = new GlideRecord('x_lsmcb_fm_room');
                grRoom.addQuery('floor.building', buildingSysID);
                grRoom.addQuery('floor', floorSysID);
                grRoom.query();
                while (grRoom.next()) {
                    for (var i = 0; i < roomList.length; i++) {
                        if (grRoom.getValue('id') == building + '.' + floor + '.' + roomList[i]) {
                            roomList.splice(i, 1);
                            break;
                        }
                    }
                }
            }

            if (roomList.length > 0) {
                var grRoomInsert = new GlideRecord('x_lsmcb_fm_room');
                roomList.forEach(function (room) {
                    grRoomInsert.initialize();
                    grRoomInsert.setValue('floor.building', buildingSysID);
                    grRoomInsert.setValue('floor', floorSysID);
                    grRoomInsert.setValue('id', building + '.' + floor + '.' + room);
                    grRoomInsert.setValue('name', room);
                    grRoomInsert.setValue('capacity', '1');
                    grRoomInsert.setValue('settings', '0');
                    grRoomInsert.insert();
                });
            }
            return true;
        }
    },

    checkoutFloorUIActionCondition: function (floor_sys_id) {
        //The UI Action should only be shown when there is no version or there is an active version and no draft version

        //Check if there is no version
        var grVersions = new GlideRecord("x_lsmcb_fm_version");
        grVersions.addQuery("record", floor_sys_id);
        grVersions.query();

        if (!grVersions.next()) { return true; }

        //Check if there is a active version
        var grActiveVersion = new GlideRecord("x_lsmcb_fm_version");
        grActiveVersion.addQuery("record", floor_sys_id);
        grActiveVersion.addQuery("status", "active");
        grActiveVersion.query();

        if (!grActiveVersion.next()) { return false; }

        //Check if there is a draft version
        var grDraftVersion = new GlideRecord("x_lsmcb_fm_version");
        grDraftVersion.addQuery("record", floor_sys_id);
        grDraftVersion.addQuery("status", "draft");
        grDraftVersion.query();

        if (!grDraftVersion.next()) { return true; }

        return false;
    },
	publishFloorUIActionCondition: function (floor_sys_id) {
        //The UI Action should only be shown when there is a draft version

        //Check if there is a active version
        var grDraftVersion = new GlideRecord("x_lsmcb_fm_version");
        grDraftVersion.addQuery("record", floor_sys_id);
        grDraftVersion.addQuery("status", "draft");
		grDraftVersion.setLimit(1);
        grDraftVersion.query();

        return (grDraftVersion.hasNext());
    },

    //deprecated
    changeLayersStatus: function (versionID, value) {
        //var grLayers = new GlideRecord("x_lsmcb_fm_layer");
        //grLayers.addQuery("record", versionID);
        //grLayers.query();

        //while (grLayers.next()) {
        //    grLayers.setValue("active", value);
        //    grLayers.update();
        //}
    }
};